require('es6-promise').polyfill();
require('isomorphic-fetch');
const fs = window.require('fs');
const path = window.require('path');
const crypto = window.require('crypto');
const md5 = require('js-md5');
const cheerio = require('cheerio');
const _ = require('underscore');

export default class Gather {
  constructor(reportCb) { // {status:,未开始 采集中 已停止 已完成, current:,count } => {}
    this.status = {
      msg: '',
      current: 0,
      count: 0
    }
    this.reportCb = reportCb
    this.going = false
    // this.enterurl = 'https://aldenparkes.com/'

  }
  check() {
    return this.status
  }
  start() {
    this.pathname = path.resolve('data/' + md5(this.enterurl))
    console.log('start',this.pathname,this.enterurl)
    this.status = {
      msg: '',
      current: 0,
      count: 0
    }
    this.going = true
    this.go()
  }
  stop() {
    this.going = false
  }
  go = async() => {
    if (!this.going) {
      this.status.msg = '已停止'
      this.reportCb(this.status)
      return
    }

    this.status.msg = '获取列表'
    this.reportCb(this.status)

    let pathname = path.resolve('data')
    if (!fs.existsSync(pathname)) {
      fs.mkdirSync(pathname)
    }

    let urls
    pathname = path.resolve('data/' + md5(this.enterurl))
    if (!fs.existsSync(pathname)) {
      fs.mkdirSync(pathname)
    }
    if (fs.existsSync(path.join(pathname, '/list.json'))) {
      console.log('load local ..', path.join(pathname, '/list.json'))
      urls =  JSON.parse(fs.readFileSync(path.join(pathname, '/list.json')))
    }else{
      urls = await this.getProductUrls()
      fs.writeFileSync(path.join(pathname, '/list.json'), JSON.stringify(urls))
    }

    this.status.msg = '获取商品'
    this.status.count = urls.length
    this.reportCb(this.status)
    for (let i of _.range(urls.length)) {
      if (!this.going) {
        this.status.msg = '已停止'
        this.reportCb(this.status)
        return
      }
      let url = urls[i]
      if(fs.existsSync(path.join(pathname, md5(url) + '.json'))){
        continue
      }else{
        console.log('fetch ', url)
        this.status.current = i + 1
        this.reportCb(this.status)
        if(url==="#")continue;
        let pd = await this.getProduct(url)
        console.log('product', pd)
        for(let im of pd.images){
          im.localfile =  path.join(this.pathname,md5(im.pic_url)+path.extname(im.pic_url))
          console.log(im.pic_url,'-->',im.localfile)
          await net2file(im.pic_url,im.localfile)
        }
        fs.writeFileSync(path.join(pathname, md5(url) + '.json'), JSON.stringify(pd))
      }
    }
    this.status.msg = '已完成'
    this.reportCb(this.status)
  }

  getProductUrls = async() => {
    alert('wrong getProductUrls')
  }
  getProduct = async(url) => {
    alert('wrong getProduct')
  }

}
const request = require("request");
let net2file = (url, filename) => {
    console.log('net2file',url,filename)
    return new Promise((resolve, reject) => {
          var options = {
            url: url,
            headers: {
              'content-length': 1024,
            }
          };
          request.head(options, function(err, res, body) {
            if (err) {
              console.log(err);
            }
            request({
              uri: url,
              encoding: 'binary'
            }, function(error, response, body) {
              if (!error && response.statusCode == 200) {
                fs.writeFile(filename, body, 'binary', function(err) {
                  if (err) {
                    console.log(err);
                  }
                  resolve()
                });
              }
            });
          });
        })
      }
